package demo1;

import java.util.*;

/**
 * @Author liangzai
 * @Description:
 */
public class Training {
    public int minimumLength(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }
        int res = 0;
        Set<Map.Entry<Character, Integer>> entries = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entries) {
            if (entry.getValue() <= 2) {
                res += entry.getValue();
            } else if (entry.getValue() > 2) {
                if (entry.getValue() % 2 == 0) {
                    res += 2;
                } else {
                    res += 1;
                }
            }
        }
        return res;
    }

    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> res = new ArrayList<>();
    int[] nums;
    int n;
    // 树枝锁set锁住i
    boolean[] set;

    public int numSquarefulPerms(int[] nums) {
        this.nums = nums;
        this.n = nums.length;
        this.set = new boolean[n];

        Set<Integer> levelLock = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (levelLock.contains(nums[i])) continue;
            set[i] = true;
            levelLock.add(nums[i]);
            dfs(i, 1);
            set[i] = false;
        }
        return res.size();
    }

    // 枚举选哪个
    // dfs定义:上一个元素下标为prevPos时，找出符合条件的剩余count个元素
    void dfs(int prevPos, int count) {
        if (count == n) {
            res.add(new ArrayList<>(path));
            return;
        }
        // 树层锁锁住nums[i]
        Set<Integer> levelLock = new HashSet<>();
        for (int i = 0; i < n; i++) {
            if (levelLock.contains(nums[i])) continue;
            if (set[i]) continue;

            levelLock.add(nums[i]);
            if (satis(i, prevPos)) {
                set[i] = true;
                dfs(i, count + 1);
                set[i] = false;
            }
        }
    }

    boolean satis(int cur, int prev) {
        double num = Math.sqrt(nums[cur] + nums[prev]);
        double floor = Math.floor(num);
        return num == floor;
    }

}
